//
//  VoiceRecordViewController.m
//  Molian
//
//  Created by wansong on 5/4/15.
//  Copyright (c) 2015 xiaocan. All rights reserved.
//

#import "VoiceRecordViewController.h"
#import "UIViewController+MJPopupViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "MLVoice.h"

#import "MLAudioRecorder.h"
#import "AmrRecordWriter.h"
#import "MLAudioPlayer.h"
#import "AmrPlayerReader.h"
#import "MLAudioMeterObserver.h"

#import "AMPopTip.h"
#import <MBProgressHUD.h>

// 音频状态
#define AUDIO_STATUS_EMPTY 0
#define AUDIO_STATUS_RECORDING 1
#define AUDIO_STATUS_NOTEMPTY 2
#define AUDIO_STATUS_PLAYING 3
#define AUDIO_STATUS_PAUSE 4
#define AUDIO_STATUS_STOP 5

#define MAX_AUDIO_RECORD_SECONDS 60


@interface VoiceRecordViewController () {
    
    NSTimer *updateAudioLengthTimer;
    NSInteger TimerLength;
    UILabel * TimerLabel;
    BOOL luyin_bool;

}


@property (strong, nonatomic) MLUser *user;

// 使用第三方的录音类
@property (nonatomic, strong) MLAudioRecorder *recorder;
@property (nonatomic, strong) AmrRecordWriter *amrWriter;

@property (nonatomic, strong) MLAudioPlayer *player;
@property (nonatomic, strong) AmrPlayerReader *amrReader;

@property (nonatomic, strong) MLAudioMeterObserver *meterObserver;

@property (strong, nonatomic) AVFile *audioFile;

@property NSUInteger audioStatus;
@property float audioLength;
@property BOOL isRecorded;

// 提示框
@property (nonatomic, strong) AMPopTip *popTip;


// 按钮
@property (nonatomic, strong) UIButton *voiceBtn;

@property (nonatomic, strong) UIButton *audioDelBtn;
@end

@implementation VoiceRecordViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.frame = CGRectMake(0, 0, 250, 200);
    self.view.backgroundColor = APPCOLORBACKGROUNDCOLOR(1);
    [self.view.layer setCornerRadius:5.0f];
    luyin_bool = NO;
    
    // 录音按钮
    self.voiceBtn = [[UIButton alloc]initWithFrame:CGRectMake(75, 40, 100, 100)];
    [self.voiceBtn setImage:[UIImage imageNamed:@"voice_record_normal"] forState:UIControlStateNormal];
    [self.voiceBtn setImage:[UIImage imageNamed:@"voice_stop"] forState:UIControlStateHighlighted];
    [self.voiceBtn addTarget:self action:@selector(audioAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.voiceBtn];
    
    // 删除按钮
    self.audioDelBtn = [[UIButton alloc]initWithFrame:CGRectMake(40, 40, 25, 25)];
    [self.audioDelBtn setImage:[UIImage imageNamed:@"voice_delete_normal"] forState:UIControlStateNormal];
    [self.audioDelBtn setImage:[UIImage imageNamed:@"voice_delete_disable"] forState:UIControlStateDisabled];
    [self.audioDelBtn addTarget:self action:@selector(deleteAudioAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.audioDelBtn];
    
    TimerLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 10, 250, 20)];
    TimerLabel.text = @"0 \"";
    TimerLabel.textAlignment = NSTextAlignmentCenter;
    TimerLabel.textColor = [UIColor grayColor];
    TimerLabel.font = [UIFont fontWithName:FontName size:13];
    [self.view addSubview:TimerLabel];
    
    
    UILabel *tishi = [[UILabel alloc]initWithFrame:CGRectMake(0, 140, 250, 20)];
    tishi.text = @"点击按钮录音";
    tishi.textAlignment = NSTextAlignmentCenter;
    tishi.textColor = [UIColor grayColor];
    tishi.font = [UIFont fontWithName:FontName size:13];
    [self.view addSubview:tishi];
    
    // 取消按钮
    UIButton *cancelBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 160, 125, 40)];
    [cancelBtn.layer setBorderColor:[UIColor lightGrayColor].CGColor];
    [cancelBtn.layer setBorderWidth:0.5f];
    [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
    [cancelBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [cancelBtn addTarget:self action:@selector(cancelVoiceAdd) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:cancelBtn];
    
    // 保存按钮
    UIButton *saveBtn = [[UIButton alloc]initWithFrame:CGRectMake(125, 160, 125, 40)];
    [saveBtn.layer setBorderColor:[UIColor lightGrayColor].CGColor];
    [saveBtn.layer setBorderWidth:0.5f];
    [saveBtn setTitle:@"保存" forState:UIControlStateNormal];
    [saveBtn setTitleColor:APPCOLOR(1) forState:UIControlStateNormal];
    [saveBtn addTarget:self action:@selector(saveVoice) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:saveBtn];
    
    // 设置初值
    self.user = [MLUser currentUser];
    // 设置录音状态
    self.audioStatus = AUDIO_STATUS_EMPTY;
    
    self.popTip = [AMPopTip popTip];
    
    // 初始化音频播放
    [self initAudioConfig];
    // 初始化音频按钮的显示
    [self updateAudioUI];
}

- (void)dealloc
{
    //音谱检测关联着录音类,录音类要停止了。所以要设置其audioQueue为nil
    self.meterObserver.audioQueue = nil;
	[self.recorder stopRecording];
    
    [self.player stopPlaying];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    if ([self isViewLoaded]&&!self.view.window) {
        self.view = nil;
    }
    // Dispose of any resources that can be recreated.
}

#pragma mark - action

- (void)cancelVoiceAdd {
    [self dismissPopupViewControllerWithanimationType:MJPopupViewAnimationFade];
}

- (void)saveVoice {
    if (TimerLength <3) {
        [HUD Prompt:@"录音时间不能低于3秒"];
        return;
    }
    if (luyin_bool == YES) {
        [HUD Prompt:@"操作过快,请稍后再试"];
        return;
    }
    luyin_bool = YES;
    
    [updateAudioLengthTimer invalidate];
    [self.recorder stopRecording];
    self.isRecorded = YES;
    self.audioStatus = AUDIO_STATUS_NOTEMPTY;
    [self updateAudioUI];
    
    // 先上传文件
    self.audioFile = [AVFile fileWithName:@"order_audio.amr" contentsAtPath:self.amrWriter.filePath];
    [self.audioFile saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
        [HUD hideFromViewAnimated:YES];
        if (succeeded) {
            // 创建新对象
            MLVoice *voice = [MLVoice object];
            voice.voice = self.audioFile;
            voice.belong_to = self.user;
            voice.theme = self.voiceTheme;
            voice.time = self.audioLength;
            [voice saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    luyin_bool = !succeeded;
                });
                if (succeeded) {
                    self.user.isHasVoice = YES;
                    [self.user saveInBackground];
                    // 添加到声线列表中
                    [self.voiceArray addObject:voice];
                    [self.voiceFileArray addObject:self.amrWriter.filePath];
                    // 退出页面
                    [self dismissPopupViewControllerWithanimationType:MJPopupViewAnimationFade];
                    // 通知有新的声线
                    [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_TYPE_NEW_VOICE object:self userInfo:nil];
                }
            }];
        }
    }];
    [HUD setOnViewWithTitle:@"正在上传..." animated:YES];

}

- (void)deleteAudioAction {
    // 删除录音
    TimerLabel.text = @"0 \"";
    TimerLength = 0;
    [self.audioFile deleteInBackground];
    self.isRecorded = NO;
    
    // 更新显示
    self.audioLength = 0;
    self.audioStatus = AUDIO_STATUS_EMPTY;
    [self updateAudioUI];
}

#pragma mark - audio

- (void)audioAction:(UIButton *)sender {
    [self.popTip hide];
    
    // 根据当前状态执行相应操作
    switch (self.audioStatus) {
        case AUDIO_STATUS_EMPTY:
        {
             // 按下录音键开始录音
            [self.recorder startRecording];
            self.meterObserver.audioQueue = self.recorder->_audioQueue;
            
            // 更新UI
            self.audioStatus = AUDIO_STATUS_RECORDING;
            [self updateAudioUI];
            
            //启动计时器
            updateAudioLengthTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateRecordedAudioTime) userInfo:nil repeats:YES];
            break;
        }
        case AUDIO_STATUS_RECORDING:
        {
            [updateAudioLengthTimer invalidate];
            [self.recorder stopRecording];
            self.isRecorded = YES;
            self.audioStatus = AUDIO_STATUS_NOTEMPTY;
            [self updateAudioUI];
            break;
            
        }
        case AUDIO_STATUS_NOTEMPTY:
        {
            self.audioStatus = AUDIO_STATUS_PLAYING;
            [self updateAudioUI];
            // 控制音频播放
            [self.player startPlaying];
            break;
        }
        case AUDIO_STATUS_PAUSE:
            self.audioStatus = AUDIO_STATUS_PLAYING;
            [self updateAudioUI];
            [self.player startPlaying];
            break;
        case AUDIO_STATUS_PLAYING:
            self.audioStatus = AUDIO_STATUS_PAUSE;
            [self updateAudioUI];
            // 暂停播放
            [self.player stopPlaying];
            break;
            
        default:
            break;
    }
   
}

- (void)updateRecordedAudioTime
{
    TimerLength ++;
    TimerLabel.text = [NSString stringWithFormat:@"%ld \"",(long)TimerLength];
    // 更新显示时间和进度条
    if([self.recorder isRecording])
    {
        self.audioLength += 1;
        
        //限制时长为60秒
        if(self.audioLength >=  MAX_AUDIO_RECORD_SECONDS)
        {
            // 停止录音
            [updateAudioLengthTimer invalidate];
            [self.recorder stopRecording];
            self.isRecorded = YES;
            self.audioStatus = AUDIO_STATUS_NOTEMPTY;
            [self updateAudioUI];
        }
    }
}

- (void)setAudioStopBlock{
    // 音频播放完成后的回调bolck
    __weak __typeof(self)weakSelf = self;
    self.player.receiveStoppedBlock = ^{
        weakSelf.audioStatus = AUDIO_STATUS_NOTEMPTY;
        [weakSelf updateAudioUI];
    };
}


- (void)updateAudioUI
{
    // 根据audioStatus切换录音的UI
    switch (self.audioStatus) {
        case AUDIO_STATUS_EMPTY:
            [self.voiceBtn setImage:[UIImage imageNamed:@"voice_record_normal"] forState:UIControlStateNormal];
            self.audioDelBtn.hidden = YES;
            break;
        case AUDIO_STATUS_RECORDING:
            [self.voiceBtn setImage:[UIImage imageNamed:@"voice_stop"] forState:UIControlStateNormal];
            break;
        case AUDIO_STATUS_NOTEMPTY:
            self.audioDelBtn.hidden = NO;
            [self.voiceBtn setImage:[UIImage imageNamed:@"voice_play"] forState:UIControlStateNormal];
            [self.audioDelBtn setEnabled:YES];
            break;
        case AUDIO_STATUS_PLAYING:
            [self.voiceBtn setImage:[UIImage imageNamed:@"voice_pause"] forState:UIControlStateNormal];
            [self.audioDelBtn setEnabled:NO];
            break;
        case AUDIO_STATUS_PAUSE:
            [self.voiceBtn setImage:[UIImage imageNamed:@"voice_play"] forState:UIControlStateNormal];
            [self.audioDelBtn setEnabled:YES];
            break;
        case AUDIO_STATUS_STOP:
            break;
        default:
            break;
    }
}

- (void)uploadAudioFile {
    // 上传录制好的音频
    self.audioFile = [AVFile fileWithName:@"order_audio.amr" contentsAtPath:self.amrWriter.filePath];
    self.isRecorded = YES;
    [self.audioFile saveInBackground];
}


- (void)initAudioConfig {
    // 录音初始化设置
    NSString *path = NSTemporaryDirectory();
    
    AmrRecordWriter *amrWriter = [[AmrRecordWriter alloc]init];
    amrWriter.filePath = [path stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.amr", TimeStamp]];
    amrWriter.maxSecondCount = MAX_AUDIO_RECORD_SECONDS;
    amrWriter.maxFileSize = 1024 *256;
    self.amrWriter = amrWriter;
    
    MLAudioMeterObserver *meterObserver = [[MLAudioMeterObserver alloc]init];
    meterObserver.actionBlock = ^(NSArray *levelMeterStates,MLAudioMeterObserver *meterObserver){
               // NSLog(@"volume:%f",[MLAudioMeterObserver volumeForLevelMeterStates:levelMeterStates]);
    };
    meterObserver.errorBlock = ^(NSError *error,MLAudioMeterObserver *meterObserver){
        [Utils playWavName:error.userInfo[NSLocalizedDescriptionKey]];
    };
    self.meterObserver = meterObserver;
    
    MLAudioRecorder *recorder = [[MLAudioRecorder alloc]init];
    __weak __typeof(self)weakSelf = self;
    recorder.receiveStoppedBlock = ^{
        weakSelf.meterObserver.audioQueue = nil;
    };
    recorder.receiveErrorBlock = ^(NSError *error){
        weakSelf.meterObserver.audioQueue = nil;
        [Utils playWavName:error.userInfo[NSLocalizedDescriptionKey]];
    };
    
    recorder.bufferDurationSeconds = 0.5;
    recorder.fileWriterDelegate = self.amrWriter;
    
    self.recorder = recorder;
    
    self.player = [[MLAudioPlayer alloc]init];
    self.amrReader = [[AmrPlayerReader alloc]init];
    self.amrReader.filePath = self.amrWriter.filePath;
    
    self.player.fileReaderDelegate = self.amrReader;
    self.player.receiveErrorBlock = ^(NSError *error){
        [Utils playWavName:error.userInfo[NSLocalizedDescriptionKey]];
    };
    
    // 设置播放停止时的block方法
    [self setAudioStopBlock];
    
    self.isRecorded = NO;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(audioSessionDidChangeInterruptionType:)
                                                 name:AVAudioSessionInterruptionNotification object:[AVAudioSession sharedInstance]];
    
}

- (void)audioSessionDidChangeInterruptionType:(NSNotification *)notification
{
    AVAudioSessionInterruptionType interruptionType = [[[notification userInfo]
                                                        objectForKey:AVAudioSessionInterruptionTypeKey] unsignedIntegerValue];
    if (AVAudioSessionInterruptionTypeBegan == interruptionType)
    {
        NSLog(@"开始");
    }
    else if (AVAudioSessionInterruptionTypeEnded == interruptionType)
    {
        NSLog(@"结束");
    }
}

@end
